/*
 * Copyright (c) 1994-2017, Joyoung Stock CO.LTD.
 * The FWJR Project.
 * All Rights Reserved.
 */

package com.rest.business;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.JsonSyntaxException;
import com.rest.client.RestClient;
import com.rest.constant.JDConstant;
import com.rest.converter.StringTypeAdapter;
import com.rest.exception.BusinessException;
import com.rest.observer.BaseObserver;
import com.rest.observer.FileDownLoadObserver;
import com.rest.response.AddOrderResponse;
import com.rest.response.AddressDetailResponse;
import com.rest.response.AddressResponse;
import com.rest.response.AppointMentBean;
import com.rest.response.AreaResponse;
import com.rest.response.BannerListResponse;
import com.rest.response.BaseJsonResponse;
import com.rest.response.BaseListResponse;
import com.rest.response.BaseResponse;
import com.rest.response.BaseStringResponse;
import com.rest.response.ChatResponse;
import com.rest.response.CheckOrderDetailResponse;
import com.rest.response.CloudDoctorResponse;
import com.rest.response.CloudResponse;
import com.rest.response.DailyRecordDetailResponse;
import com.rest.response.DailyRecordListResponse;
import com.rest.response.DiagnoseOrderDetailResponse;
import com.rest.response.DicResponse;
import com.rest.response.Doctor;
import com.rest.response.DrugResponse;
import com.rest.response.EMSResponse;
import com.rest.response.FindPatientOrdersResponse;
import com.rest.response.HomeDeptResponse;
import com.rest.response.IMListResponse;
import com.rest.response.LoginResponse;
import com.rest.response.MedicineListResponse;
import com.rest.response.MeetingResponse;
import com.rest.response.MyFamilyListResponse;
import com.rest.response.MyFamilyResponse;
import com.rest.response.NurseConsultListResponse;
import com.rest.response.NurseListResponse;
import com.rest.response.NursingOrderDetailResponse;
import com.rest.response.NursingOrderResponse;
import com.rest.response.NursingProjectResponse;
import com.rest.response.OrderNumbersResponse;
import com.rest.response.OrderResponse;
import com.rest.response.PayResponse;
import com.rest.response.PicUploadResponse;
import com.rest.response.Prescription2Response;
import com.rest.response.PrescriptionMedhisDto;
import com.rest.response.PrescriptionResponse;
import com.rest.response.QueryProtocolResponse;
import com.rest.response.RegistrationDetailResponse;
import com.rest.response.ScheduleListResponse;
import com.rest.response.ScheduleResponse;
import com.rest.response.StringResponse;
import com.rest.response.SwitchResponse;
import com.rest.response.TeamDetailResponse;
import com.rest.response.TeamListResponse;
import com.rest.response.UserResponse;
import com.rest.response.VersionResponse;
import com.rest.response.WxPayBean;
import com.rest.response.YSGCardInfoResponse;
import com.rest.util.JsonUtil;
import com.rest.util.MD5Coder;
import com.rest.util.RxUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import jz.joyoung.robot.util.LogUtil;
import jz.joyoung.robot.util.UtilString;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;


public class RestProxy {
    private static final String TAG = "jd-" + RestProxy.class.getSimpleName();

    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    private IRestAPI mRestApi;

    private Gson gson;
    private RequestBody requestBody;

    private static class SingletonHolder {
        private static final RestProxy INSTANCE = new RestProxy();
    }

    /**
     * 获取单例
     */
    public static RestProxy getInstance() {
        return SingletonHolder.INSTANCE;
    }

    private RestProxy() {
        OkHttpClient okHttpClient = RestClient.getInstance().getOkHttpClient();

        Retrofit retrofitRms = new Retrofit.Builder()
                .client(okHttpClient)
                .baseUrl(JDConstant.HOST)
                .addConverterFactory(GsonConverterFactory.create(buildGson()))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();

        mRestApi = retrofitRms.create(IRestAPI.class);
    }

    /**
     * 增加后台返回""和"null"的处理
     * 1.int=>0
     * 2.double=>0.00
     * 3.long=>0L
     *
     * @return
     */
    public Gson buildGson() {
        if (gson == null) {
            gson = new GsonBuilder()
                    .serializeNulls()
                    .registerTypeAdapter(Integer.class, new IntegerDefault0Adapter())
                    .registerTypeAdapter(int.class, new IntegerDefault0Adapter())
                    .registerTypeAdapter(Double.class, new DoubleDefault0Adapter())
                    .registerTypeAdapter(double.class, new DoubleDefault0Adapter())
                    .registerTypeAdapter(Long.class, new LongDefault0Adapter())
                    .registerTypeAdapter(long.class, new LongDefault0Adapter())
                    .registerTypeAdapter(String.class, new StringTypeAdapter())
                    .create();
        }
        return gson;
    }

    public static class IntegerDefault0Adapter implements JsonSerializer<Integer>, JsonDeserializer<Integer> {

        @Override
        public Integer deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            try {
                if (json.getAsString().equals("") || json.getAsString().equals("null")) {
                    //定义为int类型,如果后台返回""或者null,则返回0
                    return 0;
                }
            } catch (Exception ignore) {
            }
            try {
                return json.getAsInt();
            } catch (NumberFormatException e) {
                throw new JsonSyntaxException(e);
            }
        }

        @Override
        public JsonElement serialize(Integer src, Type typeOfSrc, JsonSerializationContext context) {
            return new JsonPrimitive(src);
        }
    }

    public static class LongDefault0Adapter implements JsonSerializer<Long>, JsonDeserializer<Long> {

        @Override
        public Long deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            try {
                if (json.getAsString().equals("") || json.getAsString().equals("null")) {
                    //定义为long类型,如果后台返回""或者null,则返回0
                    return 0L;
                }
            } catch (Exception ignore) {
            }
            try {
                return json.getAsLong();
            } catch (NumberFormatException e) {
                throw new JsonSyntaxException(e);
            }
        }

        @Override
        public JsonElement serialize(Long src, Type typeOfSrc, JsonSerializationContext context) {
            return new JsonPrimitive(src);
        }
    }

    public static class DoubleDefault0Adapter implements JsonSerializer<Double>, JsonDeserializer<Double> {

        @Override
        public Double deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            try {
                if (json.getAsString().equals("") || json.getAsString().equals("null")) {
                    //定义为double类型,如果后台返回""或者null,则返回0.00
                    return 0.00;
                }
            } catch (Exception ignore) {
            }
            try {
                return json.getAsDouble();
            } catch (NumberFormatException e) {
                throw new JsonSyntaxException(e);
            }
        }

        @Override
        public JsonElement serialize(Double src, Type typeOfSrc, JsonSerializationContext context) {
            return new JsonPrimitive(src);
        }
    }

    /**
     * 封装RequestBody
     */
    RequestBody getRequestBody(String str) {
        return RequestBody.create(MediaType.parse("application/json; charset=utf-8"), str);
    }

    /**
     * 显式时间 00:00
     *
     * @param hour 小时数
     * @param min  分钟数
     * @return 时间 00:00
     */
    public String formatTime(int hour, int min) {
        return String.format(Locale.getDefault(), "%02d:%02d", hour, min);
    }

    /**
     * 生成签名
     */
    private String getSign(String str, byte[] data, String salt) {
        if (TextUtils.isEmpty(str)) {
            LogUtil.w(TAG, "Empty param!");
            return null;
        }

        byte[] strBytes;
        byte[] saltBytes;
        try {
            saltBytes = salt.getBytes(StandardCharsets.UTF_8);
            strBytes = str.getBytes(StandardCharsets.UTF_8);
        } catch (NullPointerException e) {
            e.printStackTrace();
            return null;
        }

        int strLength = strBytes.length;
        int dataLength = data == null ? 0 : data.length;
        int saltLength = saltBytes.length;
        byte[] valuesBytes = new byte[strLength + dataLength + saltLength];
        System.arraycopy(strBytes, 0, valuesBytes, 0, strLength);
        if (dataLength > 0) {
            System.arraycopy(data, 0, valuesBytes, strLength, dataLength);
        }
        System.arraycopy(saltBytes, 0, valuesBytes, strLength + dataLength, saltLength);
        MD5Coder md5Coder = new MD5Coder();
        return md5Coder.encrypt2Str(valuesBytes);
    }

    public void login(String username, String password, String mobileNum, Observer<LoginResponse> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("userName", username)
                .add("password", password)
                .build();

        mRestApi.login(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void addFeedback(String feedback, Observer<String> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("feedback", feedback)
//                .add( "diagnoseId", diagnoseId )
                .build();

        mRestApi.addFeedback(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }


    public void getUserInfo(Observer<UserResponse> subscriber) {
        mRestApi.getUserInfo()
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void uploadFileTb(String bucket, String type, String objectName, String relationId, String fileSize, String isIm, Observer<PicUploadResponse> subscriber) {
        // bucket:   1-病历 2-评论(反馈) 3-头像 4-轮播图 9-聊天图片 ',
        // type:   15-病历 2-评论(反馈) 30-头像 92-聊天图片 ',
        Map<String, Object> map = new HashMap<>();//body  map

        map.put("bucket", bucket);
        map.put("type", type);
        map.put("objectName", objectName);
        map.put("introduction", "image/png");
        map.put("relationId", relationId);
        map.put("size", fileSize);
        map.put("isIm", isIm);
        map.put("checkStatus", "0");
        String json = new Gson().toJson(map);
        RequestBody requestBody = RequestBody.create(JSON, json);

        mRestApi.uploadFileTb(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void uploadFile(String bucket, String type, String relationId, File file1, Observer<PicUploadResponse> subscriber) {
        MultipartBody.Builder multipartBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("bucket", bucket)
                .addFormDataPart("type", type)
//                .addFormDataPart( "relationId", "1" )
                .addFormDataPart("relationId", relationId)
                .addFormDataPart("checkStatus", "0");

        if (file1 != null) {
            multipartBody.addFormDataPart("file", file1.getName(), RequestBody.create(MediaType.parse("image/jpg"), file1));
        }
        RequestBody requestBody = multipartBody.build();
        mRestApi.uploadFile(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void uploadVideo(File file1, Observer<PicUploadResponse> subscriber) {
        MultipartBody.Builder multipartBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("bucket", "9")
                .addFormDataPart("type", "93");
//                .addFormDataPart("relationId", "1")
//                .addFormDataPart("checkStatus", "0");

        if (file1 != null) {
            multipartBody.addFormDataPart("file", file1.getName(), RequestBody.create(MediaType.parse("application/octet-stream"), file1));
        }
        RequestBody requestBody = multipartBody.build();

        mRestApi.uploadVideo(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void downloadFile(String url, final String destDir, final String fileName, final FileDownLoadObserver<File> fileDownLoadObserver) {
        mRestApi.downloadFile(url).map(new Function<ResponseBody, File>() {
            @Override
            public File apply(ResponseBody responseBody) throws Exception {
                return fileDownLoadObserver.saveFile(responseBody, destDir, fileName);
            }
        }).compose(RxUtil.applySchedulers())
                .subscribe(fileDownLoadObserver);
    }

    public void updatePassword(String password, String newPassword, Observer<String> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("password", password)
                .add("newPassword", newPassword)
                .build();

        mRestApi.updatePassword(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void getCode(String phone, Observer<String> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("phone", phone)
                .build();

        mRestApi.getMessageCode(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void register(String name, String idcard, String password, String code, String phone, String province, String city, String region, String addr, Observer<String> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("phone", phone)
                .add("name", name)
                .add("idcard", idcard)
                .add("password", password)
                .add("code", code)
                .add("province", province)
                .add("city", city)
                .add("region", region)
                .add("addr", addr)
                .build();

        mRestApi.register(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void forget(String password, String code, String phone, Observer<String> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("phone", phone)
                .add("password", password)
                .add("code", code)
                .build();

        mRestApi.forget(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void queryIMList(String patientUserId, Observer<IMListResponse> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("patientUserId", patientUserId)
                .add("current", "1")
                .add("size", "100")
                .build();

        mRestApi.queryIMList(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void getDepartmentList(String name, Observer<List<Doctor>> subscriber) {
        FormBody.Builder requestBody = new FormBody.Builder();
        if (!TextUtils.isEmpty(name)) {
            requestBody.add("name", name);
        }
        mRestApi.getDepartmentList(requestBody.build())
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void getDoctorList(String id, Observer<List<Doctor>> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("id", id)
                .build();

        mRestApi.getDoctorList(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void getChatList(String diagnoseId, String current, Observer<ChatResponse> subscriber) {

        RequestBody requestBody = new FormBody.Builder()
                .add("diagnoseId", diagnoseId)
                .add("current", current)
                .add("size", "100")
                .build();

        mRestApi.getChatList(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    /**
     * 公用接口 查看患者自述（包括患者自述相关、聊天公用数据）
     *
     * @param diagnoseId 诊断id(Long)
     * @param subscriber subscriber
     */
    public void getRegistrationDetail(String diagnoseId, Observer<RegistrationDetailResponse> subscriber) {

        RequestBody requestBody = new FormBody.Builder()
                .add("diagnoseId", diagnoseId)
                .build();

        mRestApi.getRegistrationDetail(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void savePatientState(String patientId, String receiverDocId, String oneselfState, String allergyHistory, String pastHistory, String resourceIdList, String diagnoseId, Observer<String> subscriber) {

        RequestBody requestBody = new FormBody.Builder()
                .add("patientId", patientId)
                .add("receiverDocId", receiverDocId)
                .add("oneselfState", oneselfState)
                .add("allergyHistory", allergyHistory)
                .add("pastHistory", pastHistory)
                .add("resourceIdList", resourceIdList)
                .add("diagnoseId", diagnoseId)
                .build();

        mRestApi.savePatientState(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void addOrder(int graphicType, String doctorId, String patientId, String orderAmount, Observer<OrderResponse> subscriber) {

//        JSONObject jsonObject = new JSONObject();
//        try {
//            jsonObject.put("doctorId", doctorId);
//            jsonObject.put("patientId", patientId);
//            jsonObject.put("orderAmount", orderAmount);
//            jsonObject.put("orderType", "1");
//            jsonObject.put("doctorId", doctorId);
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
        RequestBody requestBody = new FormBody.Builder()
                .add("doctorId", doctorId)
                .add("patientId", patientId)
                .add("orderAmount", orderAmount)
                .add("orderType", "1")
                .add("businessType", String.valueOf(graphicType))
                .build();

        mRestApi.addOrder(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void addFamily(String name, String idcard, String phone, String addr, String relation, String isDefault, String province, String city, String region, Observer<String> subscriber) {

        RequestBody requestBody = new FormBody.Builder()
                .add("name", name)
                .add("idcard", idcard)
                .add("phone", phone)
                .add("addr", addr)
                .add("relation", relation)
                .add("isDefault", isDefault)
                .add("province", province)
                .add("city", city)
                .add("region", region)
                .add("isDelete", "1")
                .build();

        mRestApi.addFamily(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void getMyFamily(String userId, Observer<List<MyFamilyListResponse>> subscriber) {

        RequestBody requestBody = new FormBody.Builder()
                .add("userId", userId)
                .build();

        mRestApi.getMyFamily(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void getCloudList(String userId, String orderStatus, Observer<List<CloudResponse>> subscriber) {

        RequestBody requestBody = new FormBody.Builder()
                .add("userId", userId)
                .add("orderStatus", orderStatus)
                .build();

        mRestApi.getCloudList(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void getPhotoDoctorList(String deptId, String content, String code, String diagType, String current, String size, String isPrescription, Observer<CloudDoctorResponse> subscriber) {

        RequestBody requestBody = new FormBody.Builder()
                .add("deptId", deptId)
                .add("content", content)
                .add("code", code)
//                .add( "scheduleTime", scheduleTime )
//                .add( "timeInterval", timeInterval )
                .add("diagType", diagType)
                .add("current", current)
                .add("size", size)
                .add("isPrescription", isPrescription)
                .build();

        mRestApi.getCloudDoctorList(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }


    public void getNurseList(String content, String current, String size, Observer<NurseListResponse> subscriber) {

        Map<String, Object> map = new HashMap<>();//body  map
        map.put("name", content);
        map.put("size", size);
        map.put("current", current);
        String json = new Gson().toJson(map);
        RequestBody requestBody = RequestBody.create(JSON, json);


        mRestApi.getNurseList(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    /**
     * 获取科室列表
     *
     * @param flag       0返回推荐科室 ,1返回全部科室(Integer)
     * @param subscriber subscriber
     */

    public void getHomeDeptList(String flag, Observer<List<HomeDeptResponse>> subscriber) {
        mRestApi.getHomeDeptList(flag)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void getHelpList(Observer<List<HomeDeptResponse>> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
//                .add( "category", "help_code" )
                .build();

        mRestApi.getHelpList(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void getHelpDetailList(String type, String tital, Observer<BannerListResponse> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("type", type)
                .add("tital", tital)
                .build();

        mRestApi.getHelpDetailList(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void getEyeHospitalList(String hosDeviceId, String hosName, Observer<List<BaseListResponse>> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("hosDeviceId", hosDeviceId) //医院设备id
                .add("hosName", hosName)
                .build();

        mRestApi.getEyeHospitalList(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }


    public void getDoctorDetail(String id, Observer<Doctor> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("id", id)
                .build();

        mRestApi.getDoctorDetail(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void queryProtocol(String rulesType, Observer<QueryProtocolResponse> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("type", rulesType)
                .build();

        mRestApi.queryProtocol(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void getScheduleList(String docId, String deptId, String schDate, String timeInterval, String businessType, Observer<ScheduleListResponse> subscriber) {
        Map<String, Object> map = new HashMap<>();//body  map
        map.put("businessType", businessType);
        map.put("dockingType", "1");
        map.put("docId", docId);
        map.put("deptId", deptId);
        map.put("schDate", schDate);
        map.put("timeInterval", timeInterval);
        String json = new Gson().toJson(map);
        RequestBody requestBody = RequestBody.create(JSON, json);

        mRestApi.getScheduleList(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void createCloudOrder(String userId, String scheduleId, String patientId, String oneselfState, String allergyHistory, String pastHistory, String resourceId, Observer<OrderResponse> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("userId", userId)
                .add("scheduleId", scheduleId)
                .add("patientId", patientId)
                .add("allergyHistory", allergyHistory)
                .add("pastHistory", pastHistory)
                .add("oneselfState", oneselfState)
                .add("resourceId", resourceId)
                .build();

        mRestApi.createCloudOrder(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void setCloudReady(String userId, String id, String isReady, Observer<String> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("userId", userId)
                .add("id", id)
                .add("isReady", isReady)
                .build();

        mRestApi.setCloudReady(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }


    public void getMedicineOrderList(String userId, String current, Observer<MedicineListResponse> subscriber) {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        map.put("current", current);
        map.put("size", "10");
        String json = new Gson().toJson(map);

        RequestBody requestBody = RequestBody.create(JSON, json);

        mRestApi.getMedicineOrderList(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void cancelOrder(String orderId, Observer<String> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("orderId", orderId)
                .build();

        mRestApi.cancelOrder(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void getMedicineOrderDetail(String orderId, Observer<PrescriptionResponse> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("orderId", orderId)
                .build();

        mRestApi.getMedicineOrderDetail(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void getConsultationList(String userId, String orderStatus, Observer<List<CloudResponse>> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("userId", userId)
                .add("orderStatus", orderStatus)
                .build();

        mRestApi.getConsultationList(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void getProvince(Observer<List<AreaResponse>> subscriber) {
        mRestApi.getProvince()
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void getCity(String id, Observer<List<AreaResponse>> subscriber) {
        mRestApi.getCity(id)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void getArea(String id, Observer<List<AreaResponse>> subscriber) {
        mRestApi.getArea(id)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void getDicList(Observer<List<DicResponse>> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("category", "doc_job_title")
                .build();

        mRestApi.getDicList(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void getDepartment2List(Observer<List<DicResponse>> subscriber) {
        FormBody.Builder requestBody = new FormBody.Builder();

        mRestApi.getDepartment2List(requestBody.build())
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void getDepartment3List(String level, String parentId, String name, Observer<List<DicResponse>> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("level", level)
                .add("parentId", parentId)
                .add("name", name).build();

        mRestApi.getDepartment3List(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void userSchedule(String numberId, String patientId, String docId, String deptId, String businessType, Observer<StringResponse> subscriber) {
        Map<String, Object> map = new HashMap<>();//body  map
        map.put("businessType", businessType);
        map.put("dockingType", "1");
        map.put("numberId", numberId);
        map.put("patientId", patientId);
        map.put("docId", docId);
        map.put("deptId", deptId);
        map.put("regDocId", patientId);

        String json = new Gson().toJson(map);
        RequestBody requestBody = RequestBody.create(JSON, json);

        mRestApi.useSchedule(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void createOrder(String orderId, String orderAmount, String receiveId, String getType, Observer<PayResponse> subscriber) {
        if (!UtilString.isEmpty(receiveId)) {
            requestBody = new FormBody.Builder()
                    .add("orderId", orderId)
                    .add("orderAmount", orderAmount)
                    .add("receiveId", receiveId)
                    .build();
        } else {
            requestBody = new FormBody.Builder()
                    .add("orderId", orderId)
                    .add("orderAmount", orderAmount)
                    .add("getType", getType)
                    .build();
        }

        mRestApi.createOrder(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void getCloudOrderDetail(String orderId, Observer<CloudResponse> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("orderId", orderId)
                .build();

        mRestApi.getCloudOrderDetail(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void getAddressList(String userId, Observer<List<AddressResponse>> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("userId", userId)
                .build();

        mRestApi.getAddressList(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void addAddress(String id, String consigneeName, String consigneePhone, String addr, String isDefault, String province, String city, String region, String isDelete, Observer<String> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("id", id)
                .add("consigneeName", consigneeName)
                .add("consigneePhone", consigneePhone)
                .add("addr", addr)
                .add("isDefault", isDefault)
                .add("province", province)
                .add("city", city)
                .add("region", region)
                .add("isDelete", isDelete)
                .build();

        mRestApi.addAddress(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void getAddressDetail(String id, Observer<AddressDetailResponse> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("id", id)
                .build();

        mRestApi.addressDetail(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void updateDiagnoseStatus(String doctorUserId, String diagnoseId, String status, Observer<String> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("doctorUserId", doctorUserId)
                .add("diagnoseId", diagnoseId)
                .add("status", status)
                .build();

        mRestApi.updateDiagnoseStatus(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void updatePatientDiagnoseStatus(String diagnoseId, String status, Observer<String> subscriber) {

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("diagnoseId", diagnoseId);
            jsonObject.put("isRefuse", status);
        } catch (Exception e) {
            e.printStackTrace();
        }

        mRestApi.updatePatientDiagnoseStatus(getRequestBody(jsonObject.toString()))
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void getMyFamilyDetail(String patientId, Observer<MyFamilyResponse> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("id", patientId)
                .build();

        mRestApi.getMyFamilyDetail(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void getYSGCardInfo(String patientId, Observer<YSGCardInfoResponse> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("patientId", patientId)
                .build();

        mRestApi.getYSGCardInfo(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void bindCard(String patientId, String code, String hosPhoneNo, Observer<String> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("patientId", patientId)
                .add("code", code)
                .add("hosPhoneNo", hosPhoneNo)
                .build();

        mRestApi.bindCard(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void createCard(String patientId, String code, Observer<String> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("patientId", patientId)
                .add("code", code)
                .build();

        mRestApi.createCard(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void updatePhone(String patientId, String phone, String resourceIds, Observer<String> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("patientId", patientId)
                .add("phone", phone)
                .add("resourceIds", resourceIds)
                .build();

        mRestApi.updatePhone(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void getPicOrderDetail(String orderId, Observer<CloudResponse> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("orderId", orderId)
                .build();

        mRestApi.getPicOrderDetail(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void finishMeeting(String patientUserId, String diagnoseId, String doctorUserId, String conferenceId, String meetingType, Observer<String> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("patientUserId", patientUserId)
                .add("diagnoseId", diagnoseId)
                .add("doctorUserId", doctorUserId)
                .add("conferenceId", conferenceId)
                .add("meetingType", meetingType)
                .add("systemType", "1")//1：移动 2：华为smc
                .build();

        mRestApi.finishMeeting(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void getPrescription(String preId, Observer<Prescription2Response> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("id", preId)
                .build();

        mRestApi.getPrescription(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void queryOrderStatus(String orderId, Observer<String> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("orderId", orderId)
                .build();

        mRestApi.queryOrderStatus(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void updateTop(String diagnoseId, String status, Observer<String> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("diagnoseId", diagnoseId)
                .add("status", status)
                .add("userType", "0")
                .build();

        mRestApi.updateTop(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void getTeamList(Observer<List<TeamListResponse>> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .build();

        mRestApi.getTeamList(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void getTeamDetail(String id, Observer<TeamDetailResponse> subscriber) {
        mRestApi.getTeamDetail(id)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void updateUmengDevice(String mobileNum, String mobileType, Observer<String> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("mobileNum", mobileNum)
                .add("mobileType", mobileType)
                .build();

        mRestApi.updateUmengDevice(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void getPushMeeting(String diagnoseId, String conferenceId, String conferenceNum, String phoneId, String meetingType, Observer<MeetingResponse> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("diagnoseId", diagnoseId)
                .add("conferenceId", conferenceId)
                .add("conferenceNum", conferenceNum)
                .add("systemType", "1")
                .add("phoneId", phoneId)
                .build();


        mRestApi.getPushMeeting(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void diagnoseOrderDetail(String diagnoseId, Observer<DiagnoseOrderDetailResponse> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("diagnoseId", diagnoseId)
                .build();

        mRestApi.diagnoseOrderDetail(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void evaluateOrder(String orderId, String score, String comment, Observer<String> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("orderId", orderId)
                .add("score", score)
                .add("comment", comment)
                .build();

        mRestApi.evaluateOrder(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void delFamily(String id, Observer<String> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("id", id)
                .build();

        mRestApi.delFamily(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void getPatientDetail(String id, Observer<MyFamilyResponse> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("id", id)
                .build();

        mRestApi.getPatientDetail(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void getDailyList(Observer<List<DailyRecordListResponse>> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .build();

        mRestApi.getDailyList(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void getDailyDetail(String outpId, Observer<DailyRecordDetailResponse> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("outpId", outpId)
                .build();

        mRestApi.getDailyDetail(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void cancelDaily(String outpId, Observer<String> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("outpId", outpId)
                .build();

        mRestApi.cancelDaily(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void refund(String orderNumber, Observer<String> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("orderNumber", orderNumber)
                .add("isAdmin", "0")
                .build();

        mRestApi.refund(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void getResourcePrice(String doctorId, Observer<StringResponse> subscriber) {
        //bizType 1 是图文咨询
        mRestApi.getResourcePrice("1", doctorId)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void getVersion(Observer<VersionResponse> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("source", "1")
                .add("type", "0")
                .build();

        mRestApi.getVersion(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void getBannerList(Observer<BannerListResponse> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .build();

        mRestApi.getBannerList(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void getOrderNumbers(String userId, BaseObserver<List<OrderNumbersResponse>> subscriber) {
        mRestApi.getOrderNumbers(userId)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void changeNickName(String editData, Observer<String> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("nickName", editData)
                .build();

        mRestApi.changeNickName(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void getPresignedUrl(String bucket, Observer<String> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("bucket", bucket)
                .build();

        mRestApi.getPresignedUrl(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void createCheck(RequestBody requestBody, Observer<BaseJsonResponse> subscriber) {
        mRestApi.createCheck(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void queryCheckList(String current, String size, Observer<BaseJsonResponse> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("current", current)
                .add("size", size)
                .build();

        mRestApi.queryCheckList(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void cancelCheck(String checkFormDetailId, Observer<String> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("checkFormDetailId", checkFormDetailId)
                .build();

        mRestApi.cancelCheck(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void queryCheckDetail(String checkDetailId, Observer<BaseJsonResponse> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("checkDetailId", checkDetailId)
                .build();

        mRestApi.queryCheckDetail(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void editCheckDetail(String checkDetailId, List<BaseJsonResponse.Impression> impression, Observer<BaseJsonResponse> subscriber) {
        Map<String, Object> map = new HashMap<>();//body  map
        map.put("checkDetailId", checkDetailId);
        map.put("impression", impression);
        String json = new Gson().toJson(map);
        RequestBody requestBody = RequestBody.create(JSON, json);

        mRestApi.editCheckDetail(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void updatePrescriptionStatus(Map<String, Object> map, Observer<Boolean> subscriber) {
        mRestApi.updatePrescriptionStatus(JsonUtil.listToJson(map))
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void getPrescriptionMedhisDtoByIdApp(String diagnoseId, Observer<PrescriptionMedhisDto> subscriber) {
        mRestApi.getPrescriptionMedhisDtoByIdApp(diagnoseId)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void queryResponseList(String prescriptionId, Observer<List<EMSResponse>> subscriber) {
        mRestApi.queryResponseList(prescriptionId)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void modifyUserStatus(String orderNumber, Observer<String> subscriber) {

        Map<String, Object> map = new HashMap<>();
        map.put("userStatus", "0");
        map.put("userSource", "1");

        mRestApi.modifyUserStatus(JsonUtil.listToJson(map))
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }


    public void getNursingItemLists(String chargeItemType, Observer<NursingProjectResponse> subscriber) {
        mRestApi.getItemList(chargeItemType)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void addNursingAppointment(AppointMentBean appointMentBean, Observer<AddOrderResponse> subscriber) {
        mRestApi.addNursingAppointment(appointMentBean)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void getNursingOrders(int page, Observer<NursingOrderResponse> subscriber) {
        mRestApi.getNursingOrders(page)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void getNursingOrderDetail(long appointmentId, Observer<NursingOrderDetailResponse> subscriber) {
        mRestApi.getNursingOrderDetail(appointmentId)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void nurseRequestPay(String orderId, String orderAmount, Observer<WxPayBean> subscriber) {
        Map<String, Object> map = new HashMap<>();
        map.put("orderId", orderId);
        map.put("orderAmount", orderAmount);
        String json = new Gson().toJson(map);

        RequestBody requestBody = RequestBody.create(JSON, json);

        mRestApi.nurseRequestPay(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void appointmentComment(String appointmentId, String commentContent, int commentScore, Observer<String> subscriber) {
        Map<String, Object> map = new HashMap<>();
        map.put("appointmentId", appointmentId);
//        map.put("docId", docId);
        map.put("commentContent", commentContent);
        map.put("commentScore", commentScore);
        String json = new Gson().toJson(map);

        RequestBody requestBody = RequestBody.create(JSON, json);

        mRestApi.appointmentComment(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }


    public void queryAppointmentOrderStatus(String orderId, Observer<String> subscriber) {
        Map<String, Object> map = new HashMap<>();
        map.put("orderId", orderId);
        String json = new Gson().toJson(map);

        RequestBody requestBody = RequestBody.create(JSON, json);

        mRestApi.queryAppointmentOrderStatus(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void appointmentCancle(String orderId, Observer<String> subscriber) {
        Map<String, Object> map = new HashMap<>();
        map.put("orderId", orderId);
        map.put("type", 1);
        map.put("refundReason", "");
        String json = new Gson().toJson(map);

        RequestBody requestBody = RequestBody.create(JSON, json);

        mRestApi.appointmentCancle(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }


    public void queryPrepaidOrder(String orderId, Observer<String> subscriber) {
        Map<String, Object> map = new HashMap<>();
        map.put("orderId", orderId);
        String json = new Gson().toJson(map);

        RequestBody requestBody = RequestBody.create(JSON, json);

        mRestApi.queryPrepaidOrder(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    /**
     * 云门诊——医生列表
     *
     * @param deptId         科室id 全部传 “”
     * @param diagType       就诊类型:0:图文咨询和云门诊 1：图文咨询 3:云门诊 4门诊挂号
     * @param content        医生姓名、科室名称、医院名称、医生擅长，职称
     * @param scheduleTime   时间
     * @param timeInterval   am:上午pm：下午
     * @param current        当前页
     * @param code           职称code（字典列表返回的code）传0，查全部职称
     * @param size           页数大小
     * @param isRecommend    是否查询推荐 0查询所有 1仅查询推荐
     * @param isPrescription 处方权限 1：有 0：无
     * @param subscriber     subscriber
     */
    public void getCloudDoctorList(String deptId, String content, String scheduleTime, String timeInterval, String diagType, String current, String size, String isRecommend, String code, String isPrescription, Observer<CloudDoctorResponse> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("deptId", deptId)
                .add("content", content)
                .add("scheduleTime", scheduleTime)
                .add("timeInterval", timeInterval)
                .add("diagType", diagType)
                .add("current", current)
                .add("isRecommend", isRecommend)
                .add("isPrescription", isPrescription)
                .add("code", code)
                .add("size", size)
                .build();

        mRestApi.getCloudDoctorList(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void getCloudDoctorListIsPrescription(String deptId, String content, String scheduleTime, String timeInterval, String diagType, String current, String size, String isPrescription, String code, Observer<CloudDoctorResponse> subscriber) {
        RequestBody requestBody = new FormBody.Builder()
                .add("deptId", deptId)
                .add("content", content)
                .add("scheduleTime", scheduleTime)
                .add("timeInterval", timeInterval)
                .add("diagType", diagType)
                .add("current", current)
                .add("size", size)
                .add("isPrescription", isPrescription)
                .add("code", code)
                .build();

        mRestApi.getCloudDoctorList(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    /**
     * app首页头搜索（疾病/医生/科室）
     *
     * @param content        医生姓名、科室名称、疾病
     * @param deptId         科室id 全部传 “”
     * @param diagType       就诊类型: 0:图文咨询和云门诊 1：图文咨询 3:云门诊 4门诊挂号
     * @param code           职称id  全部传 “”
     * @param isPrescription 处方权限1：有 0：无
     * @param current        当前页数
     * @param size           页数大小
     * @param subscriber     subscriber
     */
    public void queryDoctors(String content, String deptId, String diagType, String code, String isPrescription, String current, String size, Observer<CloudDoctorResponse> subscriber) {
        Map<String, Object> map = new HashMap<>();//body  map
        map.put("content", content);
        map.put("deptId", deptId);
        map.put("diagType", diagType);
        map.put("code", code);
        map.put("isPrescription", isPrescription);
        map.put("current", current);
        map.put("size", size);

        String json = new Gson().toJson(map);

        RequestBody requestBody = RequestBody.create(JSON, json);

        mRestApi.queryDoctors(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void searchDrug(String keyWords, int page, Observer<DrugResponse> subscriber) {
//        Map<String, Object> map = new HashMap<>();//body  map
//        map.put("keyWords", keyWords);
//        String json = new Gson().toJson(map);
//        RequestBody requestBody = RequestBody.create(JSON, json);
        mRestApi.searchDrug(keyWords, page)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void createAppointNurseOrder(
            String patientId,
            String nurseId,
            String reason,
            String isAllergy,
            String allergyHistory,
            String pastHistory,
            String tbUserId,
            String resourceId, Observer<BaseResponse> subscriber) {

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("patientId", patientId);
            jsonObject.put("nurseId", nurseId);
            jsonObject.put("reason", reason);
            jsonObject.put("isAllergy", isAllergy);
            jsonObject.put("allergyHistory", allergyHistory);
            jsonObject.put("pastHistory", pastHistory);
            jsonObject.put("tbUserId", tbUserId);
            jsonObject.put("resourceId", resourceId);

        } catch (Exception e) {
            e.printStackTrace();
        }
        mRestApi.createAppointNurseOrder(getRequestBody(jsonObject.toString()))
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void findPatientOrders(int current, int size, Observer<FindPatientOrdersResponse> subscriber) {
        mRestApi.findPatientOrders(current, size)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void cancleNurseConsult(String diagnoseId, Observer<String> subscriber) {

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("diagnoseId", diagnoseId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        mRestApi.cancleNurseConsult(getRequestBody(jsonObject.toString()))
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void evaluateConsultOrder(String orderId, String comment, String score, Observer<String> subscriber) {


        RequestBody requestBody = new FormBody.Builder()
                .add("orderId", orderId)
                .add("score", score)
                .add("comment", comment)
                .build();

        mRestApi.evaluateConsultOrder(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void getNurseConsultDetail(String diagnoseId, Observer<RegistrationDetailResponse> subscriber) {
        mRestApi.getNurseConsultDetail(diagnoseId)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }


    public void queryNurseConsultList(int current, int size, Observer<NurseConsultListResponse> subscriber) {

        mRestApi.queryNurseConsultList(current, size)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }


    public void patientMedicalRecords(String patientId, Observer<Boolean> subscriber) {

        mRestApi.patientMedicalRecords(patientId)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void logOut(Observer<String> subscriber) {
        Map<String, Object> map = new HashMap<>();//body  map
        mRestApi.logOut(JsonUtil.listToJson(map))
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void getAlipaySwitch(Observer<SwitchResponse> subscriber) {

        mRestApi.getAlipaySwitch()
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }


    public void registerHePing(String numberId, String patientId, Observer<ScheduleResponse> subscriber) {
        Map<String, Object> map = new HashMap<>();
        map.put("numberId", numberId);
        map.put("patientId", patientId);
        String json = new Gson().toJson(map);
        RequestBody requestBody = RequestBody.create(JSON, json);
        mRestApi.registerHePing(requestBody)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    public void getCheckoutOrderDetail(String orderId, Observer<CheckOrderDetailResponse> subscriber) {
        mRestApi.getCheckoutOrderDetail(orderId)
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

    /**
     *
     * @param id 医技id
     * @param type 1取消订单 2-申请退费 3-撤销开单 4-取消申请退费
     * @param subscriber
     */
    public void changeStatus(String id,int type, Observer<BaseResponse> subscriber) {
        mRestApi.changeStatus(id,type)
                .map(response -> {
                    LogUtil.d(TAG, "Response => " + response);

                    if (!response.isSuccessful()) {
                        LogUtil.d(TAG, "Response => " + response.message);
                        throw new BusinessException(response.code, response.message);
                    }
                    return response;
                })
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }

    public void reportViolations(String diagnoseId,String context, Observer<String> subscriber) {

        Map<String, Object> map = new HashMap<>();
        map.put("diagnoseId",diagnoseId);
        map.put("context", context);
        map.put("type", "1");

        mRestApi.reportViolations(JsonUtil.listToJson(map))
                .compose(RxUtil.flatResponse())
                .compose(RxUtil.applySchedulers())
                .subscribe(subscriber);
    }

}
